import ua.edu.nuos.androidtraining2013.kms.dto.AuditoriumContainer;
import ua.edu.nuos.androidtraining2013.kms.dto.PermissionContainer;
import ua.edu.nuos.androidtraining2013.kms.dto.PersonnelContainer;
import ua.edu.nuos.androidtraining2013.kms.util.JSONUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

public class ServerUtility {

    private JSONStructure structure;

    private class JSONStructure {
        List<AuditoriumContainer> auditoriumList;
        List<PermissionContainer> permissionList;
        List<PersonnelContainer> personnelList;
    }

    private String inputStreamToString(InputStream inputStream) throws IOException {
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String read = bufferedReader.readLine();
        while (read != null) {
            stringBuilder.append(read);
            read = bufferedReader.readLine();
        }
        return stringBuilder.toString();
    }

    ServerUtility(String httpURL) throws IOException {
        URL url = new URL(httpURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        InputStream inputStream = connection.getInputStream();
        String jsonFromURL = inputStreamToString(inputStream);
        inputStream.close();
        connection.disconnect();
        structure = JSONUtil.fromJson(jsonFromURL, JSONStructure.class);
    }

    public List<AuditoriumContainer> getAuditoriumList() {
        return structure.auditoriumList;
    }

    public List<PermissionContainer> getPermissionList() {
        return structure.permissionList;
    }

    public List<PersonnelContainer> getPersonnelList() {
        return structure.personnelList;
    }

}
